package com.chuanyang.driverh.mainhome.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.mainhome.adapter.DriverJoinApply2Adapter;
import com.chuanyang.driverh.response2.GoodsMsgEntity;
import com.chuanyang.driverh.response2.join.ResultDriverApplyList;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.liaoinstan.springview.swipeListview.BaseSwipListAdapter;
import com.liaoinstan.springview.swipeListview.SwipeMenu;
import com.liaoinstan.springview.swipeListview.SwipeMenuCreator;
import com.liaoinstan.springview.swipeListview.SwipeMenuItem;
import com.liaoinstan.springview.swipeListview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class DriverApply2Fragment extends Fragment {

    private List<ResultDriverApplyList.DataBean> driverApplyData = new ArrayList<>();
    private SwipeMenuListView lv_my_apply;
    private AppAdapter mAdapter;

    private String fleet = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View  view = inflater.inflate(R.layout.fragment_driver_apply2, container, false);

        initView(view);



        return view;
    }

    private void initView(View view){
        lv_my_apply = (SwipeMenuListView) view.findViewById(R.id.lv_my_apply);
        lv_my_apply.setMenuCreator(creator);
        lv_my_apply.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        //删除加盟，调用删除的接口
                        updateIsVisible(driverApplyData.get(position).getBusinessId()+"");
                        break;
                }
                return false;
            }
        });

        mAdapter  = new AppAdapter();
        lv_my_apply.setAdapter(mAdapter);


        // set SwipeListener
        lv_my_apply.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        // set MenuStateChangeListener
        lv_my_apply.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
            @Override
            public void onMenuOpen(int position) {
            }

            @Override
            public void onMenuClose(int position) {
            }
        });

        if(getActivity().getIntent().getStringExtra("fleet") != null){
            fleet = getActivity().getIntent().getStringExtra("fleet");
            if(fleet.equals("1")){//车队
                selectApplyInfo("","2", SharedPrefUtil.getFleetId());
            }else if(fleet.equals("2")){//司机
                selectApplyInfo(SharedPrefUtil.getUserId(),"1","");
            }
        }


    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            deleteItem.setWidth(dp2px(90));
            deleteItem.setTitle("删除");
            deleteItem.setTitleColor(Color.WHITE);
            deleteItem.setTitleSize(18);
            menu.addMenuItem(deleteItem);
        }
    };

    class AppAdapter extends BaseSwipListAdapter {

        @Override
        public int getCount() {
            return driverApplyData.size();
        }

        @Override
        public ResultDriverApplyList.DataBean getItem(int position) {
            return driverApplyData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getContext(),
                        R.layout.driver_apply_item2, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            ResultDriverApplyList.DataBean item = getItem(position);
            holder.tv_title.setText(item.getFleetName());
//            holder.tv_goods_standard.setText(item.getGoodsStandard());
//            holder.tv_unit.setText(item.getGoodsUnit());

            return convertView;
        }

        class ViewHolder {

            ImageView iv_photo;
            TextView tv_title;
            TextView tv_jiameng_num;
            TextView tv_apply_jiameng;
            public ViewHolder(View view) {
                iv_photo = (ImageView) view.findViewById(R.id.iv_photo);
                tv_title = (TextView) view.findViewById(R.id.tv_title);
                tv_jiameng_num = (TextView) view.findViewById(R.id.tv_jiameng_num);
                tv_apply_jiameng = (TextView) view.findViewById(R.id.tv_apply_jiameng);
                view.setTag(this);
            }
        }

        @Override
        public boolean getSwipEnableByPosition(int position) {
//            if(position % 2 == 0){
//                return false;
//            }
            return true;
        }
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 删除申请
     * @param id
     */
    private void updateIsVisible(String id){
        DialogUtil.showLoadingDialog(getActivity(),"加载中...");
        Map<String,Object> paramssss =new HashMap<String, Object>();
        paramssss.put("businessId", id);
        paramssss.put("type", "");//1：司机 2：车队长

        MyHttpUtil.updateIsVisible(getActivity(),paramssss, new MyCallback<Result>(
                getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                Toast.makeText(getActivity(),"删除失败",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onSuccess(Result result, int id) {

                if(result.getCode() == ConstUtil.OK){
                    Toast.makeText(getActivity(),"删除成功",Toast.LENGTH_SHORT).show();
                    //重新请求申请列表
                    if(getActivity().getIntent().getStringExtra("fleet") != null){
                        fleet = getActivity().getIntent().getStringExtra("fleet");
                        if(fleet.equals("1")){//车队
                            selectApplyInfo("","2", SharedPrefUtil.getFleetId());
                        }else if(fleet.equals("2")){//司机
                            selectApplyInfo(SharedPrefUtil.getUserId(),"1","");
                        }
                    }
                }else {
                    Toast.makeText(getActivity(),"删除失败",Toast.LENGTH_SHORT).show();
                }
                LogUtils.d(result.getCode()+result.getMsg());

            }
        });
    }

    /**
     * 查看申请栏信息接口
     * @param id
     */
    private void selectApplyInfo(String id,String type,String fleetId){
        DialogUtil.showLoadingDialog(getActivity(),"加载中...");
        Map<String,Object> paramssss =new HashMap<String, Object>();
        paramssss.put("type", type);//1：司机 2：车队长
        paramssss.put("driverId", id);
        paramssss.put("showType", "2");
        paramssss.put("fleetId", fleetId);
        MyHttpUtil.selectApplyInfo(getActivity(),paramssss, new MyCallback<ResultDriverApplyList>(
                getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {

            }
            @Override
            public void onSuccess(ResultDriverApplyList result, int id) {
                if (result.getCode() == ConstUtil.OK ) {
                    try {
                        driverApplyData.addAll(result.getData());
                        mAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                    }
                }else{
                    if (!StringUtil.isBlank(result.getMsg()))
                        PrintUtil.toast(getActivity(),result.getMsg());
                }

            }
        });
    }
}
